package com.cn.longdistancebusstation.scenic.order;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.BuildConfig;
import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.Contacter;
import com.cn.longdistancebusstation.model.ListResultV;
import com.cn.longdistancebusstation.model.QRCodeResult;
import com.cn.longdistancebusstation.model.Result;
import com.cn.longdistancebusstation.model.ScenicOrderDetails;
import com.cn.longdistancebusstation.model.ScenicOrderList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by mucheng on 2018/4/19.
 */

public class PreUseOrderDetails2Activity extends BaseActivity implements View.OnClickListener{
    private TextView mOrderStatusTextView;
    private ImageView mQrcodeImageView;
    private TextView mVoucherCodeTextView;
    private TextView mOrderTitleTextView;
    private TextView mOrderTotalPriceTextView;
    private ImageView mOrderNoteImageView;
    private TextView mOrderIdTextView;
    private TextView mOnlineOrderTimeTextView;
    private ScenicOrderDetails mScenicOrderDetails;
    private TextView mUseSituationTextView;
    private RecyclerView mRecyclerView;
    private Button mRefundButton;
    private TouristAdapter mTouristAdapter;
    private String strTicketId;
    private String status;
    private String touristName,touristCardNo,touristTelephone;
    private ArrayList<Contacter> mContactersList=new ArrayList<>();
    private String imageUrl;
    private String strNum,strRealNum,mPftOrderNum;
    private String mOrderId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pre_use_order_detail2);
        getTitleTextView().setText("订单详情");
        initView();
    }



    private void initView() {
        Intent in=getIntent();
        strTicketId=in.getStringExtra("orderId");
        status=in.getStringExtra("status");
        mPftOrderNum=in.getStringExtra("pftId");
        mOrderStatusTextView=(TextView)findViewById(R.id.ticket_status);
        if("1".equals(status)){
            mOrderStatusTextView.setText("待使用");
        }
        mQrcodeImageView=(ImageView)findViewById(R.id.image_qrcode);
        mVoucherCodeTextView=(TextView)findViewById(R.id.voucher_code);
        mOrderTitleTextView=(TextView)findViewById(R.id.ticket_name);
        mOrderTotalPriceTextView=(TextView)findViewById(R.id.ticket_amount_price);
        mOrderNoteImageView=(ImageView)findViewById(R.id.order_note);
        mOrderNoteImageView.setOnClickListener(this);
        mOrderIdTextView=(TextView)findViewById(R.id.ticket_number);
        mOnlineOrderTimeTextView=(TextView)findViewById(R.id.order_time);
        mUseSituationTextView=(TextView)findViewById(R.id.use_situation);
        mRefundButton=(Button)findViewById(R.id.button_refund);
        mRefundButton.setOnClickListener(this);
        mRecyclerView=(RecyclerView)findViewById(R.id.tourist_list);
        mTouristAdapter=new TouristAdapter();
        mRecyclerView.setAdapter(mTouristAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    }
    private void getOrderDetails() {
        showHud();
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        Call<ListResultV<ScenicOrderDetails>> call=httpService.getScenicOrderDetails(strTicketId);
        call.enqueue(new Callback<ListResultV<ScenicOrderDetails>>() {
            @Override
            public void onResponse(Call<ListResultV<ScenicOrderDetails>> call, Response<ListResultV<ScenicOrderDetails>> response) {
                hideHud();
                ListResultV result=response.body();
                if(result.getHead().getSuccess()) {
                    Gson gson = new Gson();
                    Map<String, String> scenicMap = result.getBody().getData();
                    Type type = new TypeToken<ScenicOrderDetails>() {
                    }.getType();
                    String strScenicOrderJSON = new Gson().toJson(scenicMap);
                    mScenicOrderDetails = gson.fromJson(strScenicOrderJSON, type);
                    imageUrl=mScenicOrderDetails.getQrcodeIMG();
//                    Picasso.with(PreUseOrderDetails2Activity.this).load(mScenicOrderDetails.getQrcodeIMG()).placeholder(R.mipmap.pre_loading)
//                            .error(R.mipmap.pre_loading).noFade().into(mQrcodeImageView);
                    mVoucherCodeTextView.setText(mScenicOrderDetails.getCode());
                    mOrderTitleTextView.setText(mScenicOrderDetails.getPltitle()+"("+mScenicOrderDetails.getTtitle()+")"+mScenicOrderDetails.getNum()+"张");
                    mOrderTotalPriceTextView.setText(mScenicOrderDetails.getTotalPrice()+"元");
                    mOrderId=mScenicOrderDetails.getOrderId();
                    mOrderIdTextView.setText(mScenicOrderDetails.getOrderId());
                    mOnlineOrderTimeTextView.setText(mScenicOrderDetails.getCreateTime());
                    strNum=mScenicOrderDetails.getNum()+"";
                    strRealNum=mScenicOrderDetails.getRealNum()+"";
                    mUseSituationTextView.setText("共"+strNum+"张"+"，"+"已使用"+strRealNum+"张");
                    touristName=mScenicOrderDetails.getOrdername();
                    touristCardNo=mScenicOrderDetails.getPersonID();
                    touristTelephone=mScenicOrderDetails.getOrdertel();
                    String[] names = touristName.split(",");
                    String[] phones = touristTelephone.split(",");
                    String[] cardNos = touristCardNo.split(",");
                    String[] imagePath=imageUrl.split("\'");

                    for(int i=0; i<names.length; i++)
                    {
                        String strName = names[i];
                        String strPhone = phones[i];
                        String strCardNo = cardNos[i];
                        Contacter contacter = new Contacter();

                        contacter.setName(strName);
                        contacter.setTelephone(strPhone);
                        contacter.setCardNo(strCardNo);
                        mContactersList.add(contacter);
                    }
                    mTouristAdapter.notifyDataSetChanged();
                    getQRCodeImg();
                }
            }

            @Override
            public void onFailure(Call<ListResultV<ScenicOrderDetails>> call, Throwable t) {

            }
        });
    }
    /*
    * 获取验证用二维码
    * */
    private void getQRCodeImg() {
        String strRequestURL = mScenicOrderDetails.getQrcodeIMG();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(BuildConfig.SERVER_URL).addConverterFactory(ScalarsConverterFactory.create()).build();
        HttpService service=retrofit.create(HttpService.class);
        Call<String> call=service.getQRCode(strRequestURL);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                String strImgPath = response.body();
                String[] arr = strImgPath.split("\'");
                Picasso.with(PreUseOrderDetails2Activity.this).load(arr[1]).placeholder(R.mipmap.pre_loading)
                        .error(R.mipmap.pre_loading).noFade().into(mQrcodeImageView);
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.order_note:
                Intent in=new Intent(PreUseOrderDetails2Activity.this,ScheduleNoteActivity.class);
                startActivity(in);
                break;
            case R.id.button_refund:
                refund();
                break;
        }

    }

    private void refund() {
        showHud("正在退票，请稍后");
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        Call<Result> call=httpService.refund(mPftOrderNum,strTicketId,mScenicOrderDetails.getRealNum()+"");
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                hideHud();
                Gson gson=new Gson();
                Result result=response.body();
                if(result!=null){
                    Boolean isSuccess=result.getHead().getSuccess();
                    if(isSuccess){
                        Toast.makeText(PreUseOrderDetails2Activity.this,"退票成功",Toast.LENGTH_SHORT).show();
                        Intent in=new Intent(PreUseOrderDetails2Activity.this,RefundTicketActivity.class);
                        in.putExtra("orderId",mOrderId);
                        startActivity(in);
                        finish();
                    }else{
                        Toast.makeText(PreUseOrderDetails2Activity.this,"退票失败",Toast.LENGTH_SHORT).show();
                    }

                }

            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                hideHud();
                Toast.makeText(PreUseOrderDetails2Activity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private class TouristAdapter extends RecyclerView.Adapter<TouristViewHolder>{

        @Override
        public TouristViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(PreUseOrderDetails2Activity.this);
            View view = layoutInflater.inflate(R.layout.tourist_info_recycle_item, parent, false);
            return new TouristViewHolder(view);
        }

        @Override
        public void onBindViewHolder(TouristViewHolder holder, int position) {
            Contacter contacter=mContactersList.get(position);
            holder.bindData(contacter);


        }

        @Override
        public int getItemCount() {
            return mContactersList.size();
        }
    }

    private class TouristViewHolder extends RecyclerView.ViewHolder{
        private TextView mTouristNameTextView;
        private TextView mTouristIdcardNoTextView;
        private TextView mtouristTelephoneTextView;
        public TouristViewHolder(View itemView) {
            super(itemView);
            mTouristNameTextView=(TextView)itemView.findViewById(R.id.tourist_name);
            mTouristIdcardNoTextView=(TextView)itemView.findViewById(R.id.idcard_numbers);
            mtouristTelephoneTextView=(TextView)itemView.findViewById(R.id.telephone_number);
        }

        public void bindData(Contacter contacter) {
            mTouristNameTextView.setText(contacter.getName());
            mTouristIdcardNoTextView.setText(contacter.getCardNo());
            mtouristTelephoneTextView.setText(contacter.getTelephone());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getOrderDetails();
    }
}
